<template>
  <glsx-dialog :show="value" title="更新成交" width="60%" @close="closeDialog">
    <el-form class="el_form" ref="addForm" :model="addForm" :rules="addFormRules" :key="randomKey" size="small"
      label-width="120px">
      <div class="top_info">
        <el-form-item label="客户姓名：">{{ info.name }}</el-form-item>
        <el-form-item label="客户手机：">{{ info.phone }}</el-form-item>
        <el-form-item label="预约门诊：">{{ info.hospitalName }}</el-form-item>
        <el-form-item label="预约时间：">{{ info.appointmentTime }}</el-form-item>
      </div>
      <el-form-item label="成交情况：" prop="dealStatus">
        <el-radio-group v-model="addForm.dealStatus" @change="onChange">
          <el-radio :label="8">是</el-radio>
          <el-radio :label="7">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="addForm.dealStatus == 8">
        <el-form-item label="成交项目：" prop="dealProject">
          <el-select v-model="addForm.dealProject" multiple placeholder="请选择" class="a_select">
            <el-option v-for="(item, index) in projectList" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="报名费处理：" prop="enrollFeeHandle">
          <el-radio-group v-model="addForm.enrollFeeHandle">
            <el-radio v-for="(item,index) in DEALENROLLFEELIST" :key="index" :label="item.id">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="收款情况：" prop="dealType">
          <el-radio-group v-model="addForm.dealType">
            <el-radio :label="1">全款</el-radio>
            <el-radio :label="2">部分款</el-radio>
            <el-radio :label="3">定金</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="成交金额：" prop="dealAmount">
          <el-input type="text" v-model.number="addForm.dealAmount" class="a_input"></el-input>
          <span class="tips">含报名费，若定金客户不确定成交金额，成交金额按照定金金额写</span>
        </el-form-item>
        <el-form-item label="收款金额：" prop="collectMoney">
          <el-input type="text" v-model.number="addForm.collectMoney" class="a_input"></el-input>
        </el-form-item>
        <el-form-item label="收款时间：" prop="collectTime">
          <el-date-picker v-model="addForm.collectTime" :picker-options="pickerOptions" class="a_input" type="datetime"
            placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </template>
      <el-form-item label="门诊反馈：" prop="outpatientFeedback">
        <el-input type="textarea" v-model="addForm.outpatientFeedback" rows="5" maxlength="1500" resize="none"
          class="a_area"></el-input>
      </el-form-item>
      <el-form-item label="有无潜在成交：" prop="potentialDeal">
        <el-radio-group v-model="addForm.potentialDeal">
          <el-radio :label="0">无</el-radio>
          <el-radio :label="1">有</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注：" v-if="addForm.dealStatus == 8">
        <el-input type="textarea" v-model="addForm.remark" rows="5" maxlength="1500" resize="none" class="a_area">
        </el-input>
      </el-form-item>
      <el-form-item label="未成交原因：" v-if="addForm.dealStatus == 7" prop="undealReason">
        <el-input type="textarea" v-model="addForm.undealReason" rows="5" maxlength="1500" resize="none" class="a_area">
        </el-input>
      </el-form-item>
      <!-- <el-form-item>
        <div class="btn_group">
          <el-button type="primary" size="small" :loading="bloading" @click="saveInfo(true)">保存并写回访记录</el-button>
          <el-button type="default" size="small" :loading="loading" @click="saveInfo()">保存</el-button>
        </div>
      </el-form-item> -->
    </el-form>
    <div slot="footer">
      <el-button type="primary" size="small" :loading="bloading" @click="saveInfo()">保存</el-button>
      <el-button type="default" size="small" :loading="bloading" @click="closeDialog()">取消</el-button>
    </div>
  </glsx-dialog>
</template>
<script>
import { GETPROJECTOPTIONS, GETFOLLOWRULES } from "@/http/system";
import { ORDERARRIVED } from "@/http/book";
import { deepClone, showToast } from "@/common/util";
import { DEALENROLLFEELIST } from "@/common/constants";
import moment from "moment";
import { Validator } from "@/common/validator";
export default {
  name: "ShopUpdate",
  props: {
    info: {
      type: Object,
      default: function () {
        return {};
      },
    },
    value: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    info: {
      handler: function (n, m) {
        this.init(n)
      },
      immediate: true
    }
  },
  data() {
    return {
      addForm: { dealStatus: 8, dealProject: [], enrollFeeHandle: 1 },
      projectList: [],
      addFormRules: {
        dealStatus: [
          { required: true, message: "请选择成交情况", trigger: "change" },
        ],
        dealProject: [
          { required: true, message: "请选择成交项目", trigger: "change" },
        ],
        enrollFeeHandle: [
          { required: true, message: "请选择报名费处理", trigger: "change" },
        ],
        dealType: [
          { required: true, message: "请选择收款情况", trigger: "change" },
        ],
        dealAmount: [
          { required: true, message: "请输入成交金额", trigger: "blur" },
          { type: "number", message: "成交金额必须为数字", trigger: "blur" },
          {
            pattern: Validator.ISDECIMAL,
            message: "成交金额不能为负数",
            trigger: "blur",
          },
        ],
        collectMoney: [
          { required: true, message: "请输入收款金额", trigger: "blur" },
          { type: "number", message: "收款金额必须为数字", trigger: "blur" },
          {
            pattern: Validator.ISDECIMAL,
            message: "收款金额不能为负数",
            trigger: "blur",
          },
        ],
        collectTime: [
          { required: true, message: "请输入收款时间", trigger: "blur" },
        ],
        outpatientFeedback: [
          { required: true, message: "请输入门诊反馈", trigger: "blur" },
        ],
        potentialDeal: [
          { required: true, message: "请选择有无潜在成交", trigger: "change" },
        ],
        undealReason: [
          { required: true, message: "请输入未成交原因", trigger: "blur" },
        ],
      },
      loading: false,
      pickerOptions: {
        // disabledDate: function (e) {
        //   let min = moment().subtract(7, "days").format("x");
        //   let n = moment(e).format("x");
        //   if (n < min) {
        //     return true;
        //   }
        //   if (e.getTime() > Date.now()) {
        //     return true;
        //   }
        // },
      },
      bloading: false,
      DEALENROLLFEELIST: DEALENROLLFEELIST,
      randomKey: "",
      rules: {},
    };
  },
  created() {
    this.getRules();
  },
  mounted() {
    this.getProject();
  },
  methods: {

    // 初始化参数
    init(n) {
      if (!n) {
        return false;
      }
      console.log(n)

      let o = deepClone(this.addForm);

      o.dealStatus = n.dealStatus || 8
      o.dealProject = n.dealProject || []
      o.dealAmount = n.dealAmount
      o.collectMoney = n.collectMoney
      //o.collectTime = n.collectTime
      o.outpatientFeedback = n.feedbackContent

      if (n.feedbackTime) {
        o.collectTime = n.feedbackTime
      }
      this.addForm = o;
    },

    // 获取所有项目
    getProject() {
      GETPROJECTOPTIONS().then((res) => {
        this.projectList = res.data || [];
      });
    },

    // 获取配置规则
    getRules() {
      let _this = this;
      GETFOLLOWRULES().then((res) => {
        this.rules = res.data || {};
        let obj = res.data || {};

        let disabledDate = function (e) {
          let min = moment()
            .subtract(obj.arrivedDealLimitDays, "days")
            .format("x");
          let n = moment(e).format("x");
          if (n < min) {
            return true;
          }
          if (e.getTime() > Date.now()) {
            return true;
          }
        };
        _this.$set(_this.pickerOptions, "disabledDate", disabledDate);
      });
    },

    // 保存数据
    saveInfo(type) {
      let _this = this;
      let loadingId = "loading";
      if (type) {
        loadingId = "bloading";
      }

      
      _this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false;
        }

        let m = deepClone(_this.addForm);

        // 如果是全款，则收款金额必须等于成交金额
        if (m.dealType == 1 && m.dealAmount != m.collectMoney) {
          showToast({
            message: "收款金额必须等于成交金额",
          });
          return false;
        }

        // 如果是定金，则收款金额必须小于等于成交金额
        if (m.dealType == 3 && m.collectMoney > m.dealAmount) {
          showToast({
            message: "收款金额不能大于成交金额",
          });
          return false;
        }

        let oParams = {};
        // 未成交
        if (m.dealStatus == 7) {
          oParams.dealStatus = m.dealStatus;
          oParams.outpatientFeedback = m.outpatientFeedback;
          oParams.undealReason = m.undealReason;
        }

        // 已成交
        if (m.dealStatus == 8) {
          oParams = { ...m };
          oParams.dealProject = oParams.dealProject.toString();
        }

        oParams.orderId = _this.info.orderId;
        oParams.potentialDeal = m.potentialDeal

        console.log(oParams);
        _this[loadingId] = true;
        ORDERARRIVED(oParams).then((res) => {
          _this[loadingId] = false;
          if (res.code == 200) {
            showToast({
              message: "保存成功",
              type: "success",
            });
            console.log(_this.info);
            let eInfo = { id: "shopDialog" };
            if (type) {
              (eInfo.openId = "shopVisitDialog"), (eInfo.oInfo = _this.info);
            }
            // _this.$emit("change", eInfo);
            _this.$emit('input', false)
          }
        });
      });
    },

    // 监听状态切换
    onChange() {
      this.$refs.addForm.clearValidate();
      this.randomKey = Math.random();
    },

    // 关闭弹框
    closeDialog() {
      this.$emit('input', false)
    }

  },
};
</script>
<style lang="scss" scoped>
.top_info {
  display: flex;
  flex-wrap: wrap;

  .el-form-item {
    flex: 0 0 50%;
  }
}

.el_form {

  .a_input,
  .a_select {
    width: 240px;
  }

  .a_area {
    width: 400px;
  }

  .tips {
    font-size: 12px;
    color: #999;
    margin: 0 0 0 10px;
  }
}
</style>